const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const User = require('../models/user');
const FaceRecognitionService = require('../services/faceRecognition');

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = path.join(__dirname, '../uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`);
  }
});

const upload = multer({ 
  storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB限制
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'));
    }
  }
});

// 注册新用户并添加人脸
router.post('/register', upload.single('image'), async (req, res) => {
  try {
    const { name, email } = req.body;
    
    if (!name || !email || !req.file) {
      return res.status(400).json({ success: false, message: '缺少必要参数' });
    }
    
    const userIdfind = await User.findById(email);
    if(userIdfind){
      return res.status(400).json({ success: false, message: '用户已存在' });
    }

    // 检测人脸
    const faceDetection = await FaceRecognitionService.detectFace(req.file.path);
    
    if (!faceDetection.success) {
      // 删除上传的文件
      fs.unlinkSync(req.file.path);
      return res.status(401).json(faceDetection);
    }
    

    // 创建用户
    const userId = await User.create(name, email);
    
    // 保存人脸描述符
    await User.saveFaceDescriptor(userId, faceDetection.descriptor, req.file.path);
    
    res.json({
      success: true,
      message: '用户注册成功',
      userId
    });
  } catch (error) {
    console.error('Error in register:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 识别人脸
router.post('/recognize', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ success: false, message: '缺少图片文件' });
    }
    
    const recognition = await FaceRecognitionService.recognizeFace(req.file.path);
    
    // 删除临时上传的文件
    fs.unlinkSync(req.file.path);
    
    res.json(recognition);
  } catch (error) {
    console.error('Error in recognize:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取所有用户
router.get('/users', async (req, res) => {
  try {
    const [rows] = await require('../config/db').execute('SELECT * FROM users');
    res.json({ success: true, users: rows });
  } catch (error) {
    console.error('Error getting users:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

module.exports = router;